# frozen_string_literal: false

<%= lines(autogen_notice(:ruby,pwd)) -%>
require 'gcp_backend'
require 'google/iam/property/iam_policy_audit_configs'
require 'google/iam/property/iam_policy_bindings'

# A provider to manage <%= @api.display_name -%> IAM Policy resources.
class <%= object.name -%>IamPolicy < GcpResourceBase
  name '<%= resource_name(object, product) -%>_iam_policy'
  desc '<%= object.name -%> Iam Policy'
  supports platform: 'gcp'

  attr_reader :params
  attr_reader :bindings
  attr_reader :audit_configs

  def initialize(params)
    super(params.merge({ use_http_transport: true }))
    @params = params
    @fetched = @connection.fetch(product_url, resource_base_url, params, '<%= object.iam_policy.fetch_iam_policy_verb.capitalize -%>'<% if object.iam_policy.iam_conditions_request_type == :REQUEST_BODY -%>, { 'options' => { 'requestedPolicyVersion' => 3 } }.to_json<% end -%>)
    parse unless @fetched.nil?
  end

  def parse
    @bindings = GoogleInSpec::Iam::Property::IamPolicyBindingsArray.parse(@fetched['bindings'], to_s)
    @audit_configs = GoogleInSpec::Iam::Property::IamPolicyAuditConfigsArray.parse(@fetched['auditConfigs'], to_s)
  end

  def exists?
    !@fetched.nil?
  end

<%
individual_url = object.iam_policy.base_url || object.self_link || object.base_url + '/{{name}}' 
identifiers = extract_identifiers(individual_url)
-%>
  def to_s
    "<%= object.name -%> IamPolicy #{@params[:<%= identifiers.last.underscore -%>]}"
  end

  def iam_binding_roles
    @bindings.map(&:role)
  end

  def count
    @bindings.size
  end

  private

  def product_url
    '<%= object.product_url || object.__product.base_url %>'
  end

<%
# snake_case all identifiers in the URL
identifiers.each do |identifier|
  individual_url = individual_url.gsub("{{#{identifier}}}", "{{#{identifier.underscore}}}")
end
-%>
  def resource_base_url
    '<%= individual_url -%><%= object.iam_policy.method_name_separator -%><%= object.iam_policy.fetch_iam_policy_method -%>'
  end
end
